package org.jflame.uid.worker.dao.impl;

import org.jflame.uid.worker.dao.IWorkerNodeDao;
import org.jflame.uid.worker.dao.WorkerNodeMapper;
import org.jflame.uid.worker.entity.WorkerNodeEntity;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class WorkerNodeMybatisImpl implements IWorkerNodeDao {

    private SqlSessionFactory sqlSessionFactory;

    public WorkerNodeMybatisImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public WorkerNodeEntity getWorkerNodeByHostPort(String host, String port) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            WorkerNodeMapper mapper = sqlSession.getMapper(WorkerNodeMapper.class);
            return mapper.getWorkerNodeByHostPort(host, port);
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public boolean registerWorkerNode(WorkerNodeEntity workerNodeEntity) {
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        int i = 0;
        try {
            WorkerNodeMapper mapper = sqlSession.getMapper(WorkerNodeMapper.class);
            i = mapper.addWorkerNode(workerNodeEntity);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
        return i > 0;
    }

}
